import os
import sys
import transaction
import paste.fixture
import paste.registry
import paste.deploy.config
from paste.deploy import loadapp, appconfig
from paste.script.command import Command, BadCommand
from paste.script.filemaker import FileOp
from tempita import paste_script_template_renderer
from tgext.zeroisp.lib import database
from tgext.zeroisp.lib import agoda_com
import pylons
import pylons.util as util

from tg import config, url

HOTEL_MAP = {'hotel_name': 'post_title',
             'hotel_description': 'post_content'}

class ImportAgoda(Command):
    # Parser configuration
    summary = "--NO SUMMARY--"
    usage = "--NO USAGE--"
    group_name = "tgglobe"
    parser = Command.standard_parser(verbose=False)

    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]
            config_name = 'config:%s' % config_file
            here_dir = os.getcwd()
            locs = dict(__name__="pylons-admin")

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
        # will automatically be initialized and restored via the registry
        # restorer along with the other StackedObjectProxys
        # Load app config into paste.deploy to simulate request config
        # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
        # code
        conf = appconfig(config_name, relative_to=here_dir)
        conf.update(dict(app_conf=conf.local_conf,
                         global_conf=conf.global_conf))
        paste.deploy.config.CONFIG.push_thread_config(conf)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the pylons.config object
        pkg_name = pylons.config['pylons.package']


        # Start the rest of our imports now that the app is loaded
        """
        if is_minimal_template(pkg_name, True):
            model_module = None
            helpers_module = pkg_name + '.helpers'
            base_module = pkg_name + '.controllers'
        else:
        """
        if True:
            model_module = pkg_name + '.model'
            helpers_module = pkg_name + '.lib.helpers'
            base_module = pkg_name + '.lib.base'

        if True:#model_module and can_import(model_module):
            locs['model'] = sys.modules[model_module]

        if True:#can_import(helpers_module):
            locs['h'] = sys.modules[helpers_module]

        exec ('from pylons import app_globals, c, config, g, request, '
              'response, session, tmpl_context, url') in locs
        exec ('from pylons.controllers.util import abort, redirect_to') in locs
        exec 'from pylons.i18n import _, ungettext, N_' in locs
        exec 'from pylons.templating import render' in locs

        # Import all objects from the base module
        __import__(base_module)

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        for name in base_public:
            locs[name] = getattr(base, name)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))
        model = locs['model']
        a=agoda_com.Agoda(config.get('agoda.username'),
                          config.get('agoda.password'), config.get('google.maps.key'))
        tot_continent=0
        tot_country=0
        tot_city=0
        tot_hotel=0
        if len(self.args) == 1:
            for cont in a.get_geocontinent():
                """
                {'continent_id': '4', 'foreign_continent_name': 'Europe', 'region_name': 'Europe'}
                """
                print "%s\t%s"%(cont['continent_id'], cont['region_name'])

        elif len(self.args) == 2:
            print "continent_id\tcountry_id\tcountry_name"
            for count in a.get_geocountry(self.args[1]):
                """
                {'continent_id': '4', 'country_name': 'United Kingdom', 'country_id': '107', 'foreign_country_name': 'United Kingdom'}
                """
                if count['continent_id'] != self.args[1]:
                    print 'ERROR - continent_id'
                    print count
                else:
                    print "%s\t%s\t%s"%( self.args[1], count['country_id'], count['country_name'] )
        if len(self.args) == 3:
            for city in a.get_geocity(self.args[2]):
                """
                {'city_id': '20019', 'city_name': 'Volterra', 'country_id': '205', 'foreign_city_name': 'Volterra'}
                """
                print "%s\t%s\t%s\t%s"%( self.args[1], city['country_id'], city['city_id'], city['city_name'] )

                tot_city += 1
                for hotel in a.get_hotel_city(city['city_id']):
                    tot_hotel += 1
                    for agoda_hotel in a.get_hotel_info(hotel['hotel_id']):
                        team = model.DBSession.query(model.Team).filter_by(team_alias='kztn').one()
                        category = model.DBSession.query(model.Category).filter_by(category_name='hotel_agoda').one()
                        lat = agoda_hotel['georeference']['Latitude']
                        lng = agoda_hotel['georeference']['Longitude']
                        one, two = a.m.reverse_search(lat,lng)
                        try:
                            address_values = two[0]

                            post_values = {}
                            post_values['post_title'] = agoda_hotel['hotel_name']
                            post_values['post_content'] = ''
                            post_values['post_description'] = ''
                            post_values['post_category_id'] = category.category_id
                            post_values['post_team_id'] = team.team_id

                            if agoda_hotel.has_key('hotel_description'):
                                try:
                                    h = model.DBSession.query(model.Hotel).filter_by(hotel_id=hotel['hotel_id']).one()
                                    post = h.post
                                except:
                                    h = model.Hotel()
                                    h.hotel_id = hotel['hotel_id']
                                    post = model.Post()

                                setattr(h, 'star_rating', agoda_hotel['star_rating'])
                                setattr(h, 'hotel_url', agoda_hotel['hotel_url'])
                                if agoda_hotel['price_from'].strip():
                                    setattr(h, 'price_from', float(agoda_hotel['price_from'].strip()))

                                setattr(h, 'hotel_room_number' , agoda_hotel['hotel_room_number' ])
                                desc = agoda_hotel['hotel_description']
                                for line in desc.split('\n'):
                                    post_values['post_content'] += "<p>%s</p>"%(line)

                                for key, val in post_values.iteritems():
                                    if hasattr(post, key):
                                        setattr(post, key, val)
                                if not post.post_address:
                                    address = model.GoogleAddress()
                                else:
                                    address = post.post_address
                                for key, val in address_values.iteritems():
                                    if hasattr(address, key):
                                        setattr(address, key, val)

                                post.hotel.append(h)
                                address.posts.append(post)
                                model.DBSession.flush()
                                model.DBSession.add(address)
                                transaction.commit()
                        except:
                            raise


            sys.exit()
"""
            for cont in a.get_geocontinent():
                tot_continent += 1
                if not os.path.exists('output_agoda'):
                os.makedirs('output_agoda')
                path_cont = os.path.join('output_agoda', cont['region_name'])
                if not os.path.exists(path_cont):
                os.makedirs(path_cont)
                for count in a.get_geocountry(cont['continent_id']):
                tot_country += 1
                path_count = os.path.join(path_cont, count['country_name'])
                if not os.path.exists(path_count):
                    os.makedirs(path_count)
                for city in a.get_geocity(count['country_id']):
                    tot_city += 1
                    path_city = os.path.join(path_count,
                        city['city_name']).encode('utf-8')
                    if not os.path.exists(path_city):
                        os.makedirs(path_city)
                    for hotel in a.get_hotel_city(city['city_id']):
                        tot_hotel += 1
                        path_hotel = os.path.join(path_city,
                        hotel['hotel_name'].encode('utf-8'))
                        print path_hotel
                        if not os.path.exists(path_hotel):
                            os.makedirs(path_hotel)
                        for agoda_hotel in a.get_hotel_info(hotel['hotel_id']):
                                team = model.DBSession.query(model.Team).filter_by(team_alias='kztn').one()
                                category = model.DBSession.query(model.Category).filter_by(category_name='hotel_agoda').one()
                        lat = agoda_hotel['georeference']['Latitude']
                                    lng = agoda_hotel['georeference']['Longitude']
                                    one, two = a.m.reverse_search(lat,lng)
                                    address_values = two[0]
                                    post_values = {}
                                    post_values['post_title'] = agoda_hotel['hotel_name']
                                    post_values['post_content'] = ''
                                    post_values['post_description'] = ''
                                    post_values['post_category_id'] = category.category_id
                                    post_values['post_team_id'] = team.team_id
                                    if agoda_hotel.has_key('hotel_description'):
                                        desc = agoda_hotel['hotel_description']
                                    for line in desc.split('\n'):
                                        post_values['post_content'] += "<p>%s</p>"%(line)
                                    post = model.Post()
                                    for key, val in post_values.iteritems():
                                        if hasattr(post, key):
                                            setattr(post, key, val)
                                    address = model.GoogleAddress()
                                    for key, val in address_values.iteritems():
                                        if hasattr(address, key):
                                            setattr(address, key, val)
                                    try:
                                        h = model.DBSession.query(model.Hotel).filter_by(hotel_id=hotel['hotel_id']).one()
                                    except:
                                        h = model.Hotel()
                                        h.hotel_id = hotel['hotel_id']
                                    post.hotel.append(h)
                                    address.posts.append(post)
                                    model.DBSession.flush()
                                    model.DBSession.add(address)
                                    transaction.commit()
"""
